package com.xiyoufang.club.utils;

import com.xiyoufang.club.repository.ClubRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;
import java.util.Random;

@Component
public class ClubComponent
{
  @Autowired
  private ClubRepository clubRepository;
  public static final int MIN_ID_NUM = 10000;
  public static final int MAX_ID_NUM = 100000;
  private static final List<Integer> unUseClubId = new LinkedList();
  private static List<Integer> usedClubId;
  
  private void initClubId()
  {
    usedClubId = this.clubRepository.findClubIdList();
    for (int clubId = 10000; clubId < 100000; clubId++) {
      if (!usedClubId.contains(Integer.valueOf(clubId))) {
        unUseClubId.add(Integer.valueOf(clubId));
      }
    }
  }
  
  public synchronized Integer getClubId()
  {
    if (unUseClubId.isEmpty()) {
      initClubId();
    }
    if (usedClubId.size() >= 90000) {
      return null;
    }
    int clubId = ((Integer)unUseClubId.remove(new Random().nextInt(unUseClubId.size()))).intValue();
    usedClubId.add(Integer.valueOf(clubId));
    return Integer.valueOf(clubId);
  }
}
